<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      class MyPromise {
        constructor(handle) {
          this["[[PromiseState]]"] = "pendding";
          this["[[PromiseResult]]"] = undefined;
          handle(this.#_resolve.bind(this), this.#_reject.bind(this));
          this.resolveFn = undefined; // 保存 onResolved 函数
          this.rejectFn = undefined; // 保存onRejected函数；
        }

        #_resolve(val) {
          this["[[PromiseState]]"] = "fulfilled";
          this["[[PromiseResult]]"] = val;
          //   模拟微任务
          let m = new MutationObserver(() => {
            this.resolveFn(val);
          });
          m.observe(document.body, {
            attributes: true,
          });
          document.body.setAttribute("myattr", "val");
        }
        #_reject(err) {
          this["[[PromiseState]]"] = "rejected"; // 改变状态
          this["[[PromiseResult]]"] = err; // 改变结果值
          setTimeout(() => {
            this.rejectFn(err);
          });
          setTimeout(() => {
            throw new Error(err); // 抛出错误
          });
        }
        then(onResolved, onRejected) {
          this.resolveFn = onResolved;
          this.rejectFn = onRejected;
        }
      }

      // 执行顺序 会先执行 resolve函数 ,之后执行then方法 然后才赋值 onResolved 及onRejected

      setTimeout(() => {
        console.log("settimeout");
      });

      let p = new MyPromise((resolve, reject) => {
        resolve("success");
      });
      console.log(111);

      p.then(
        (res) => {
          console.log("执行了onResolved", res);
        },
        (err) => {}
      ); // 调用 类里的then方法；

      console.log(222);
    </script>
  </body>
</html>
